import mockConfig from './config/index';
import { sendSuccess, sendFail } from "./utils";
import { getList, addData, updateData, deleteData, batchDeleteData, findOne } from "./utils/readFile";

const prefix = mockConfig.prefix
const tableName = 'user'

function filterByAge(list, maxAge, minAge) {
  if (typeof maxAge === 'undefined' || typeof minAge === 'undefined') {
    return list;
  }
  return list.filter(item => {
    const age = item.user?.detail?.age
    return age <= maxAge && age >= minAge
  })
}

export default [
  {
    url: `${prefix}/user/list`,
    timeout: mockConfig.timeout,
    method: "get",
    response: (ctx) => {
      const { type, maxAge, minAge, ...rest } = ctx.query
      const data = getList(tableName, rest, (list) => filterByAge(list, maxAge, minAge))
      data.list = data.list.map(item => {
        const { age, ...rest } = item
        if (!rest.user) {
          rest.user = {
            detail: {}
          }
        }
        rest.user.detail.age = age
        return rest
      })
      return sendSuccess(data);
    },
  },
  {
    url: `${prefix}/user`,
    timeout: mockConfig.timeout,
    method: "post",
    response: (ctx) => {
      const data = addData(tableName, ctx.body)
      return sendSuccess(data);
    },
  },
  {
    url: `${prefix}/user`,
    timeout: mockConfig.timeout,
    method: "put",
    response: (ctx) => {
      const data = updateData(tableName, ctx.body)
      return sendSuccess(data);
    },
  },
  {
    url: `${prefix}/user`,
    timeout: mockConfig.timeout,
    method: "delete",
    response: (ctx) => {
      const { id } = ctx.body
      if (!id && id !== 0) {
        return sendFail({}, "缺少id参数")
      }
      if (!Array.isArray(id)) {
        const data = deleteData(tableName, id)
        return sendSuccess(data);
      } else {
        const data = batchDeleteData(tableName, id)
        return sendSuccess(data);
      }
    },
  },
  {
    url: `${prefix}/user/detail`,
    timeout: mockConfig.timeout,
    method: "get",
    response: (ctx) => {
      const data = findOne(tableName, ctx.query.id)
      return sendSuccess(data);
    },
  },
];
